package cn.guyouda.algorithms;

/**
 * @author Youda
 * 二分查找
 */
public class BinarySearch {

    /**
     * 折半查找
     *
     * @param key   待查找数字
     * @param array 数组
     * @return 如果查到返回位置，否者返回-1
     */
    public static int search(double key, double[] array) {
        int low = 0;
        int high = array.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (key < array[mid]) {
                high = mid - 1;
            }

            if (key > array[mid]) {
                low = mid + 1;
            }

            if (key == array[mid]) {
                return mid;
            }
        }
        return -1;
    }
}
